<?php

class RequestSender
{
	var $logic = array();

	function RequestSender()
	{
		$req = Post::get('ajaxCall');
		if (count($req))
		{
			foreach($req as $name => $value)
			{
				if ($name == 'MD5')
				{
					continue;
				}
				$this->$name->text = $value;
			}
		}
	}
	function update()
	{
		$this->__newLogic('eval', $this->__updateParams());
		$this->__send();
	}
	function __updateParams($obj = -1, $id = '')
	{
		if ($obj == -1)
		{
			$obj = $this;
		}
		$jsGenCode = '';
		$params = get_object_vars($obj);
		if (count($params))
		{
			foreach($params as $name => $Obj)
			{
				if ($name == 'logic')
				{
					continue;
				}
				if (is_object($Obj))
				{
					$jsGenCode .= $this->__updateParams($Obj, $name);
				} else {
					$jsGenCode .= $this->__getJsCode($id, $name);
				}
			}
		}

		return $jsGenCode;
	}

	function __send()
	{
		LibManager::get("Ajax.JSON");
		$JSON = new Services_JSON();
		$AJAX = LibManager::get("Ajax.Ajax");
		$AJAX->sendJSON($JSON->encode($this->logic));
	}

	function __newLogic($type, $logic)
	{
		if (!empty($logic))
		{
			$this->logic[] = array($type, $logic);
		}
	}

	function __getJsCode($id, $name)
	{
		$jsCode = '$(\''.$id.'\')';

		if ($name == 'value' || $name == 'innerHTML')
		{
			$param = 'text';
		} else {
			$param = $name;
		}

		if ($name == 'text')
		{
			$jsCode .= '.setText(\''.$this->$id->$param.'\')';
		} else if ($name == 'style')
		{
			$styleCode = $jsCode;
			$jsCode = '';
			$jsCodeArray = array();
			$expl = explode(';', $this->$id->$param);
			array_pop($expl);
			foreach($expl as $p => $set)
			{
				$q = explode(':', trim($set));
				if (eregi('-', $q[0]))
				{
					$e = explode('-', $q[0]);
					$set = $e[0] . ucfirst($e[1]);
				} else {
					$set = $q[0];
				}
				$jsCodeArray[] = $styleCode.'.' . $param . '.'.$set.' = \''.trim($q[1]).'\'';
			}
			$jsCode .= implode(';', $jsCodeArray);
		} else {
			$jsCode .= '.' . $param . ' = \''.$this->$id->$param.'\'';
		}

		return $jsCode . ';';
	}

	function alert($txt)
	{
		$this->__newLogic('alert', $txt);
	}

}

?>